#!/bin/bash

## SCRIPT PARAMS
SLEEP=0.2

## DEBUG PRINT
echo -e "Choosen interface: " $1 "\nIP Address: " $2

## L2 params
IFACE=$1
MODE=adhoc
ESSID=mine
RATE=1Mb

## L3 params
MYIP=$2
MYMASK=255.255.255.0
MYBCAST=10.1.2.255

## ARP params
IPDST1=10.1.2.1
MACDST1=00:00:10:01:02:01
IPDST2=10.1.2.2
MACDST2=00:00:10:01:02:02

## CHECK ON IFACE TO AVOID BRINGING IT UP AND DOWN (WITH HIGH PROB. OF CRASHES).
MODESTATE=$(iwconfig  $IFACE | awk '$1 == "Mode:Ad-Hoc" {print "ISADHOC"}')

## Script
echo "Enter wifi frequency channel [1:13] (Default channel 13, 2.472GHz):"
read CHANNEL
if [ "$CHANNEL" = "" ]; then
	CHANNEL=13 #Channel 13 (LOT OF INTERFERENCE)
fi

echo "Manually set preconfigured hard coded ARP table entries [y/N]?"
NOARP=N; read NOARP

ifconfig $IFACE down
if [ "$MODESTATE" != "ISADHOC" ]; then
  sleep $SLEEP
  wlanconfig $IFACE destroy
  #some sleep time to avoid commands overlap
  sleep $SLEEP
  wlanconfig $IFACE create wlandev wifi0 wlanmode $MODE > /dev/null
fi

sleep $SLEEP
iwconfig $IFACE channel $CHANNEL essid $ESSID rate $RATE
sleep $SLEEP
ifconfig $IFACE down
sleep $SLEEP
ifconfig $IFACE $MYIP netmask $MYMASK up


#arp -d $IPDST
if [ "$NOARP" = "Y" ] || [ "$NOARP" = "y" ]; then

    ## Specify a fake node
    echo "Do you want to define a fake node (ARP fake entry) [y/N]?"
    FKARP=N;read FKARP
    if [ "$FKARP" = "Y" ] || [ "$FKARP" = "y" ]; then
      echo "Specify IP (Detault 10.1.2.5): "
      read IPDSTFK
      echo "Specify MAC (Default 00:00:10:01:02:05): "
      read MACDSTFK
      if [ "$IPDSTFK" = "" ]; then
      IPDSTFK=10.1.2.5
      fi
      if [ "$MACDSTFK" = "" ]; then
      MACDSTFK=00:00:10:01:02:05
      fi
    fi
	## Other ARP entries
	sleep $SLEEP
	arp -i ath0 -s $IPDST1  $MACDST1
	sleep $SLEEP
	arp -i ath0 -s $IPDST2  $MACDST2
	if [ "$FKARP" = "Y" ] || [ "$FKARP" = "y" ]; then
	   sleep $SLEEP
	   arp -i ath0 -s $IPDSTFK $MACDSTFK
	fi
fi
echo "Always force RTS/CTS Virtual Carrier Sensing [Y/n]?"
VCS=Y;read VCS
if [ "$VCS" = "Y" ] || [ "$VCS" = "y" ]; then
	sleep $SLEEP
	iwconfig $IFACE rts 1B
fi

## Test
echo -ne "\n\n>>> L2 parameters:\n"
iwconfig ath0
echo -ne "\n\n>>> L3 parameters:\n"
ifconfig ath0
echo -ne "\n\n>>> ARP table:\n"
arp -ne
